namespace SimpleWebServices.Web
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Net;
    using System.Web;
    using SimpleWebServices.Configuration;

    public sealed class PathRedirectionModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }

            context.BeginRequest += this.OnBeginRequest;
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Justification = "It is public for testability.")]
        public void OnBeginRequest(object sender, EventArgs e)
        {
            HttpRequestBase request = HttpContextFactory.Current.Request;
            RedirectionSetting setting = RedirectionConfiguration.Settings().Paths[request.Path];
            if (null != setting)
            {
                HttpResponseBase response = HttpContextFactory.Current.Response;
                response.StatusCode = (int)HttpStatusCode.SeeOther;
                response.AppendHeader("Location", new Uri(request.Url, (Uri)(RelativeUri)setting.To).AbsoluteUri);
                response.Cache.SetCacheability(HttpCacheability.Server);
                response.Cache.SetExpires(DateTimeFactory.UtcNow.AddDays(1));
                response.End();
            }
        }
    }
}